package home.dao.impl;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import home.model.GameInfo;
import home.model.Goods;
import home.model.Skill;
import home.model.Users;
import home.model.minUsers;

import home.dao.UsersDao;

public class UsersDaoImpl implements UsersDao{
	private SessionFactory sessionFactory;
	public UsersDaoImpl(){
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public List findByUsersIdPwd(Object une, Object pwd) {
		// TODO Auto-generated method stub
		List results = findByTwoProperty("Users","username","password",une,pwd);
		return results;
	}

	@Override
	public List findByOneProperty(String className, String property, Object value) {
		// TODO Auto-generated method stub
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String queryString = "from " + className + " where " + property + "='" + value + "'";
			Query queryObject = session.createQuery(queryString);
			List list = queryObject.list();
			if(list.size() == 0){
				return null;
			}else{
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public List findByTwoProperty(String className, String property1,
			String property2, Object value1, Object value2) {
		// TODO Auto-generated method stub
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String queryString="from " + className + " where " + property1 + "='" + value1 + "' and " + property2 + " = '" + value2 + "'";
			Query queryObject = session.createQuery(queryString);
			List list = queryObject.list();
			if(list.size() == 0){
				return null;
			}else{
				return list;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public Users findByUsername(String username) {
		// TODO Auto-generated method stub
		List<Users> results = findByOneProperty("Users","username",username);
		if(results == null) return null;
		return results.get(0);
	}

	@Override
	public Users addUsers(String username, String password, String salt,
			String name, String main_type, String sex) {
		// TODO Auto-generated method stub
		Users users = new Users();
		users.setUsername(username);
		users.setPassword(password);
		users.setSalt(salt);
		users.setName(name);
		users.setSex(sex);
		users.setPower(2);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date=new Date(System.currentTimeMillis());
		users.setCreated_at(df.format(date));
		users.setCreated_by("users/register");
		users.setUpdated_at(df.format(date));
		users.setUpdated_by("users/register");
		
		GameInfo gameInfo = new GameInfo();
		gameInfo.setHp(100);
		gameInfo.setLl(10);
		gameInfo.setMj(10);
		gameInfo.setZl(10);
		gameInfo.setMain_type(main_type);
		gameInfo.setMoney(0);
		gameInfo.setGet_money(1);
		gameInfo.setCreated_at(df.format(date));
		gameInfo.setCreated_by("users/register");
		gameInfo.setUpdated_at(df.format(date));
		gameInfo.setUpdated_by("users/register");
		
		Session session=null;
		
		int num=0;
		try{
			session=sessionFactory.openSession();
			Transaction trans=session.beginTransaction();
//			num=Integer.parseInt(session.save(gameInfo).toString());
			users.setGameInfo(gameInfo);
			num=Integer.parseInt(session.save(users).toString());
			System.out.println(num);
			trans.commit();
			return users;
		}catch(Exception ex){
			System.out.println("创建用户失败");
			ex.printStackTrace();
			return users;
		}finally{
			session.close();
		}
	}

	@Override
	public List<Users> getAllUsers() {
		// TODO Auto-generated method stub
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String queryString="from Users";
			Query queryObject = session.createQuery(queryString);
			List<Users> usersList = queryObject.list();
			if(usersList.size() == 0){
				return null;
			}else{
				return usersList;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public Users findById(int id) {
		// TODO Auto-generated method stub
		List<Users> results = findByOneProperty("Users","id",id);
		if(results == null) return null;
		return results.get(0);
	}

	@Override
	public boolean deleteUsersById(int id) {
		// TODO Auto-generated method stub
		Session session = null;
		try{
			session=sessionFactory.openSession();
			Transaction trans=session.beginTransaction();
			Users us = findById(id);
			session.delete(us);
			trans.commit();
			return true;
		}catch(Exception ex){
			System.out.println("删除用户失败");
			ex.printStackTrace();
			return false;
		}finally{
			session.close();
		}
	}

	@Override
	public boolean saveUsers(Users users) {
		// TODO Auto-generated method stub
		Session session=null;
		
		try{
			session=sessionFactory.openSession();
			Transaction trans=session.beginTransaction();
			session.saveOrUpdate(users);
			trans.commit();
			return true;
		}catch(Exception ex){
			System.out.println("修改或添加用户失败");
			ex.printStackTrace();
			return false;
		}finally{
			session.close();
		}
	}

	@Override
	public String nadianSome(Users users, String type) {
		// TODO Auto-generated method stub
		Session session = null;
		String name = "";
		try {
			System.out.println("dao type:" + type);
			session = sessionFactory.openSession();
			String queryString = "from " + type;
			Query queryObject = session.createQuery(queryString);
			List list = queryObject.list();
			
			if(list.size() == 0){
				return null;
			}else{
				int num = (int)(0+Math.random()*(list.size()-1-0+1));
				System.out.println(list + " " + num);
				
				if(type.equals("Goods")){
					Goods goods = (Goods) list.get(num);
					users.getGoodsItem().add(goods);
					name = goods.getName();
				}else if(type.equals("Skill")){
					Skill skill = (Skill) list.get(num);
					users.getSkillItem().add(skill);
					name = skill.getName();
				}
				
				Transaction trans=session.beginTransaction();
				session.merge(users);
				trans.commit();
				
				return name;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public List<minUsers> searchUsers(List<minUsers> usersList, String location) {
		// TODO Auto-generated method stub
		System.out.println(location);
		float locationX = Float.parseFloat(location.split(",")[0]);
		float locationY = Float.parseFloat(location.split(",")[1]);
		System.out.println(locationX + "  " + locationY);
		
		for(int i = usersList.size()-1;i>=0;i--){
		   float locationXX = Float.parseFloat(usersList.get(i).getLocation().split(",")[0]);
		   float locationYY = Float.parseFloat(usersList.get(i).getLocation().split(",")[1]);
		   if( Math.abs(locationX - locationXX) > 0.1 || Math.abs(locationY - locationYY) > 0.1 ){			   
			   usersList.remove(i);
		   }
		   System.out.println(locationX - locationXX);
		   System.out.println(Math.abs(locationX - locationXX) > 0.1);
		   System.out.println(Math.abs(locationX - locationXX) > 0.1 || Math.abs(locationY - locationYY) > 0.1);
		}
		System.out.println(usersList);
		
		return usersList;
	}

	@Override
	public Users randUsers() {
		// TODO Auto-generated method stub
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String queryString = "from Users";
			Query queryObject = session.createQuery(queryString);
			List list = queryObject.list();
			
			if(list.size() == 0){
				return null;
			}else{
				int num = (int)(0+Math.random()*(list.size()-1-0+1));
				System.out.println(list + " " + num);
				
				Users dfUsers = (Users) list.get(num);
				
				return dfUsers;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}

	@Override
	public String winGetSome(Users win, Users lost, String type) {
		// TODO Auto-generated method stub
		Session session = null;
		String str = "";
		try {
			System.out.println("dao type:" + type);
			session = sessionFactory.openSession();
			
				if(type.equals("Goods")){
					int goodsNum = lost.getGoodsUse().size();
					int num = (int)(Math.random()*(goodsNum));
					Goods goods = lost.getGoodsUse().remove(num);
					win.getGoodsItem().add(goods);
					str = goods.getName();
				}else if(type.equals("Skill")){
					int skillNum = lost.getSkillUse().size();
					int num = (int)(Math.random()*(skillNum));
					Skill skill = lost.getSkillUse().remove(num);
					win.getSkillItem().add(skill);
					str = skill.getName();
				}
				
				Transaction trans=session.beginTransaction();
				session.merge(win);
				session.merge(lost);
				trans.commit();
				
				return str;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
	
	public List queryForPage(final String hql,final int offset,final int length){
		Session session = null;
		try {
			session = sessionFactory.openSession();
			Query queryObject = session.createQuery(hql);
			queryObject.setFirstResult(offset);
			
			queryObject.setMaxResults(length);
			List<minUsers> usersList = queryObject.list();
			if(usersList.size() == 0){
				return null;
			}else{
				return usersList;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
    }
    
    public int getAllRowCount(String hql){
		Session session = null;
		try {
			session = sessionFactory.openSession();
			Query queryObject = session.createQuery(hql);
			
			List<minUsers> usersList = queryObject.list();
			return usersList.size();
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		} finally {
			session.close();
		}
    }

	@Override
	public minUsers findByIdFromMinUsers(int id) {
		// TODO Auto-generated method stub
		List<minUsers> results = findByOneProperty("minUsers","id",id);
		if(results == null) return null;
		return results.get(0);
	}

	@Override
	public List<minUsers> getAllMinUsers() {
		// TODO Auto-generated method stub
		Session session = null;
		try {
			session = sessionFactory.openSession();
			String queryString="from minUsers";
			Query queryObject = session.createQuery(queryString);
			List<minUsers> usersList = queryObject.list();
			if(usersList.size() == 0){
				return null;
			}else{
				return usersList;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			session.close();
		}
	}
}
